﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IceDog.Lib.IceDogLog
{
    public class IceDogLog
    {
        public static void WriteLog(string message, string group = "", object obj = null)
        {
            var logPath = System.AppDomain.CurrentDomain.BaseDirectory + @"error-log\\";
            if (!System.IO.Directory.Exists(logPath)) System.IO.Directory.CreateDirectory(logPath);
            if (System.IO.File.Exists(logPath + "off.log")) return;
            var fileName = System.DateTime.Now.ToString("yyyy-MM-dd") + ".log";
            if (!string.IsNullOrEmpty(group)) fileName = string.Concat(group, "-", fileName);
            fileName = System.IO.Path.Combine(logPath, fileName);
            var sw = new System.IO.StreamWriter(fileName, true) { AutoFlush = true };
            var head = "======[" + group + "]======[Time:" + System.DateTime.Now.ToString("hh:mm:ss") + "]======" + "\r\n>>>\r\n";
            var arr = message.Split('|');
            if (arr.Length > 1)
            {
                message = System.String.Empty;
                for (var i = 0; i < arr.Length; i++)
                {
                    message += "\r\n\r\n----- 第 " + (i + 1) + " 部分的日志 -----\r\n" + arr[i];
                }
            }
            if (obj != null)
            {
                message += "\r\n\r\n----- 属性列表 -----\r\n";
                var sb = new System.Text.StringBuilder(); var i = 0; var type = obj.GetType();
                foreach (var prop in type.GetProperties())
                {
                    ++i;
                    sb.AppendFormat("{0} - {1}.{2}:{3} \r\n", i, type.Name, prop.Name, prop.GetValue(obj, null));
                }
                message += sb.ToString();
                sb.Clear(); i = 0;
                message += "\r\n\r\n----- 字段列表 -----\r\n";
                foreach (var field in type.GetFields())
                {
                    ++i;
                    sb.AppendFormat("{0} - {1}.{2}:{3} \r\n", i, type.Name, field.Name, field.GetValue(obj));
                }
                message += sb.ToString();
            }
            var content = "LOG:" + message + "\r\n>>>\r\n";
            var foot = "======[" + group + "]======[end]======\r\n\r\n";
            var msg = head + content + foot;
            sw.Write(msg);
            sw.Close();
        }
    }
}
